using Autofac;
using Microsoft.AspNetCore.Builder;
using Serilog;
using XjjXmm.Infrastructure.Configuration;
using XjjXmm.Infrastructure.ToolKit;

namespace xjjxmm.infrastructure.SetUp;

public static class LogSetUp
{
	public static WebApplicationBuilder RegistLog(this WebApplicationBuilder builder)
	{
		Log.Information($"EnvironmentName: {builder.Environment.EnvironmentName}");
			
		//扫描本地log及从配置中心读log
		builder.WebHost.ConfigureAppConfiguration((context, configurationBuilder) =>
		{
			configurationBuilder.Scan(builder.Environment.EnvironmentName);
			configurationBuilder.AddCustom();
		});

		//serilog
		ConfigHelper.Configuration = builder.Configuration;
		
		Log.Logger = new LoggerConfiguration()
			.ReadFrom.Configuration(ConfigHelper.Configuration)
			.CreateBootstrapLogger();

        //Log.Information($"EnvironmentName2: {builder.Environment.EnvironmentName}");
        //Log.Information($"AppContext.BaseDirectory: {AppContext.BaseDirectory}");
        //Log.Information($"AppKit.GetCurrentDirectory: {AppKit.GetCurrentDirectory()}");
        //Log.Information($"Environment.CurrentDirectory: {Environment.CurrentDirectory}");

        //Console.WriteLine($"EnvironmentName2: {builder.Environment.EnvironmentName}");
        //Console.WriteLine($"AppContext.BaseDirectory: {AppContext.BaseDirectory}");
        //Console.WriteLine($"AppKit.GetCurrentDirectory: {AppKit.GetCurrentDirectory()}");
        //Console.WriteLine($"Environment.CurrentDirectory: {Environment.CurrentDirectory}");

        

        //builder.Host.UseSerilog();
        //注册级配置serilog
        builder.Host.UseSerilog((context, services, configuration) =>
		{
			configuration.ReadFrom.Configuration(ConfigHelper.Configuration);
		});

        Log.Information($"EnvironmentName3: {builder.Environment.EnvironmentName}"); 
        return builder;
	}

	public static WebApplication UseLog(this WebApplication app)
	{
		app.UseSerilogRequestLogging(); // <-- Add this line

		return app;
	}
}
